package Prova::Controller::PreOperation;

use strict;
use warnings;
use base 'Catalyst::Controller';
use Data::Dumper;

=head1 NAME

Prova::Controller::PreOperation - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 create

=cut

sub create : Private {
    my ( $self, $c ) = @_;

    my $datablock = $c->stash->{datablock};
    my $data = $c->stash->{pre_operation};

    # delete
    my $pre_operations = $c->forward( 'find_by_id', [ ( $datablock->id ) ] );
    if ( ref $pre_operations eq 'ARRAY' ) {
        for my $pre_operation ( @$pre_operations ) {
            $c->log->info( "delete pre_operation : id=".$pre_operation->id );
            $pre_operation->delete;
        }
    }

    # create
    if ( ref $data eq 'HASH' ) {
        my @new;
        for ( sort { $a <=> $b } keys %$data ) {
            $data->{$_}->{data_block_id} = $datablock->id;
            my $pre_operation = $c->model( 'DBIC::PreOperation' )->create( $data->{$_} );
            push @new, $pre_operation;
            $c->log->info( "create pre_operation : id=".$pre_operation->id );
        }
         $c->stash->{pre_operation} = \@new;
    }
}

=head2 find_by_id

=cut

sub find_by_id : Private {
    my ( $self, $c, $datablock_id ) = @_;

    my $pre_operation = [ $c->model( 'DBIC::PreOperation' )->search(
        { data_block_id => $datablock_id }
    ) ];

    return $pre_operation;
}

=head1 AUTHOR

Shanon Inc, E<lt>http://www.shanon.co.jp/E<gt>

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
